<?php
namespace backend\components\widget\editor;

use yii\helpers\Html;
use yii\web\JsExpression;
use yii\widgets\InputWidget;

/**
 * Class WangEditor
 * @property array $config
 * @package backend\components\widget\editor
 */
class WangEditor extends InputWidget
{

    /**
     * @var array
     */
    public $config = [];

    /**
     * init
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        parent::init();

        if (!isset($this->options['editorId'])) {
            $this->options['editorId'] = 'editorId_'.uniqid();
        }

    }

    /**
     * run
     * @return string|void
     */
    public function run()
    {
        $this->registerJsCode();

        $value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;

        $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name;

        return $this->render('wangEditor', [
            'name'          => $name,
            'value'         => $value,
            'options'       => $this->options,
        ]);
    }

    /**
     * registerJsCode
     */
    protected function registerJsCode()
    {
        WangEditorAsset::register($this->view);

        $editorId = $this->options['editorId'];

        $configJs = $this->getConfigJs();

        $js = <<<JS
const {$editorId} = new window.wangEditor('#{$editorId}');{$configJs}{$editorId}.create();
JS;
        $this->view->registerJs($js);
    }


    /**
     * editor.config.zIndex = 500
     * editor.config.placeholder = '自定义 placeholder 提示文字'
     * editor.config.focus = false // 取消自动 focus
     * editor.config.menus = [ // 配置菜单栏，删减菜单，调整顺序
            'bold',
            'head',
            'link',
            'italic',
            'underline'
        ]
     * @return string
     */
    protected function getConfigJs()
    {
        $inputEle = "$('#{$this->options['id']}')";


        $defaultConfig = [
            'onchange' => new JsExpression("function (html) {{$inputEle}.val(html)}"),
            'uploadImgServer' => '"/file/wand-editor-image"',
            'uploadImgMaxLength' => 5,
            //'uploadImgShowBase64' => 'true',
        ];

        $this->config = array_merge($defaultConfig,$this->config);

        $editorId = $this->options['editorId'];

        $configJs = '';
        foreach ($this->config as $key => $value){
            if(is_array($value))
                $value = json_encode($value);
            $configJs .= $editorId.'.config.'.$key.'='.$value.';';
        }

        return $configJs;
    }

}